#include <iostream>
#include "database.h"
#include "3761.h"

void parse_AFN0(Controller& controller)
{
	Frame& f = controller.recvbuf.frame;
	DataType& d = *(DataType*)controller.recvbuf.data;

	cout << __func__ << ":" << f.toString() << endl;

	switch(d.Fn())
	{
		case 0: 
		case 1:
		case 3:
				if(controller.lstate == LOGIN_SEND)
				{
					controller.lstate = LOGIN_OK;
				}
				return;
		case 4:
		case 2:return;
		break;
	}
}
void parse_AFN2(Controller& controller)
{
	Frame& f = controller.recvbuf.frame;
	cout << __func__ << ":" << f.toString() << endl;
}
void parse_AFN4(Controller& controller)
{
	Frame& f = controller.recvbuf.frame;
	cout << __func__ << ":" << f.toString() << endl;
}
void parse_AFN5(Controller& controller)
{
	Frame& f = controller.recvbuf.frame;
	cout << __func__ << ":" << f.toString() << endl;
}
void parse_AFND(Controller& controller)
{
	ActiveAfn0dParser active;
	PasiveAfn0dParser pasive;
	Buffer& b = controller.recvbuf;
	Mapmss mss;
	
	active.parse(b.data, b.dataLength());
	active.get(mss);

	cout << __func__ << ":" << mss.toString() << endl;
}
void parse_packet(Controller& controller)
{
	Frame& f = controller.recvbuf.frame;
	switch(f.function.AFN)
	{
		case 0x00: parse_AFN0(controller); return; break;
		case 0x02: parse_AFN2(controller); return; break;
		case 0x04: parse_AFN4(controller); return; break;
		case 0x05: parse_AFN5(controller); return; break;
		case 0x0D: parse_AFND(controller); return; break;
	}
	cout << __func__ << "(not know): " << f.toString() << endl;
}
int main(int argc, char **argv)
{
	Controller controller;
	string ipp = (argc > 1) ? argv[1] : "124.232.137.226:2028";

	cout << "config is "  << (Database::config.isok  ? "ok" : "bad") << endl;
	cout << "history is " << (Database::history.isok ? "ok" : "bad") << endl;

	if(controller.connect(ipp) == false)
	{
		perror("connect");
		return -1;
	}
	controller.beatInterval = 3;
	controller.address.init("4301", 256, 0);

	while(1)
	{
		controller.heatbeat();
		if(controller.receive() )
		{
			if( controller.check() )
			{
				parse_packet(controller);
				controller.recvbuf.clear();
			}
		}
		usleep(100);
		fflush(stdout);
	}

	return 0;
}
